/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package deatax.display;

import com.jogamp.opengl.util.texture.TextureData;

import com.jogamp.opengl.util.texture.awt.AWTTextureData;
import deatax.ResourceLoader;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.media.opengl.GL2;

/**
 *
 * @author nrechten
 */
public class Texture {

    protected static HashMap<String, TextureInfo> cache = new HashMap<String, TextureInfo>();
    protected static boolean initd = false;
    private String file;
    private TextureInfo ti;

    public Texture(String file) {
        this.file = file;
        if (!cache.containsKey(file)) {
            cache.put(file, null);
        }
    }

    public void bind(GL2 gl) {

        if (ti == null) {
            if (cache.containsKey(file) && cache.get(file) != null) {
                ti = cache.get(file);
            } else {
                TextureData ted = new AWTTextureData(gl.getGLProfile(), 0, 0, true, loadImage(file));
                ti = new TextureInfo(ted);
                cache.put(file, ti);
            }
        }

        if(ti != null){
            ti.bind();
            
                    gl.glTexParameterf(GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_S,GL2.GL_REPEAT );
                    gl.glTexParameterf(GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_T,GL2.GL_REPEAT );
        }
    }

    public static void cacheImages(GL2 gl) {
        for (Entry<String, TextureInfo> entry : cache.entrySet()) {
            if (entry.getValue() != null) {
                entry.getValue().reload();
            } else {
                System.out.println(entry.getKey());
                TextureData ted = new AWTTextureData(gl.getGLProfile(), 0, 0, true, loadImage(entry.getKey()));
                TextureInfo t = new TextureInfo(ted);
                entry.setValue(t);
            }

        }
    }

    public static BufferedImage loadImage(String file) {
        try {

//            File f = new File(file);
            System.out.print("Loading image : " + file);
            InputStream is = ResourceLoader.loadStream(file);
            if(is == null){ System.out.println(" - Failed");return null; }
            System.out.println(" - OK?");
            return ImageIO.read(is) ;
//            URL image_url = Main.class.getResource(file);
//            if (image_url != null) {
//                return ImageIO.read(image_url);
//            }

        } catch (IOException ex) {
        }
        return null;
    }

    public static void unbind() {
    }

    
}
